<template>
	<view class="container">
		<com-head textTit="购物车" :typeVal="1" :scrollTop="scrollTop"></com-head>
		
		<template v-if="carList.length">
			<view class="title">
				<view class="checkNum">当前已选中 <text>{{chioseGoodsNum}}</text> 件商品（共 {{carList.length}} 件）</view>
				<text class="edit" @click="idDelete = !idDelete">编辑</text>
			</view>
			<view class="shopCarWrap">
				<!--  -->
				<u-swipe-action :show="item.show" :index="index" 
					@click="deCar" @open="open"
					:options="options"
					v-for="(item, index) in carList" :key="index"
				>
				 <view class="list" v-if="carList.length">
				 	<text class="iconfont " @click="choice(item)"   :class="item.isCheck ? 'icon-a-xingzhuang1' : 'icon-weixuanzhong' "></text>
					<!--  -->
					<view class="right">
						<image @click="jump('/pages/shop/shopInfo?goods_id='+ item.sku.goods.id)" :src="item.sku.img ? item.sku.img : item.sku.goods.picture" mode=""></image>
						<view class="shopInfo">
							<view class="shopName">{{item.sku.goods.title}}</view>
							<view class="skrWrap">
								<view class="skr">{{item.sku.sku_text}}</view>
							</view>
							<view class="skrWrap">
								<view class="time"><image src="//jiudao123.oss-cn-shanghai.aliyuncs.com/store/img/shijian223.png" mode=""></image>预计{{dataTime(item.sku.goods.expect_day || 0)}}发货</view>
							</view>
							<view class="bottom">
							   <view class="price"><text>¥</text>{{item.sku.sale_price}}</view>
							   <view class="stock">库存：{{item.sku.stock}}件</view>
							   <view class="number">
							   	  <view class="reduce" @click="reduce(item)">-</view>
								  <view class="num">{{item.number}}</view>
								  <view class="plus" @click="plus(item)">+</view>
							   </view>
							</view>
						</view>
					</view>
					<view class="grayOut" v-if="item.sku.stock < 1">
						库存不足
					</view>
				 </view>
				</u-swipe-action>
			</view>
			<view class="fixedBottom">
				<view class="left" @click="allCheck()">
					<text class="iconfont " :class="isAllCheck ? 'icon-a-xingzhuang1' : 'icon-weixuanzhong' "></text>
					<text class="all">全选</text>
				</view>
				<view class="right" v-if="idDelete">
					<view class="rightR" @click="batchDele()">
						删除
					</view>
				</view>
				<view class="right" v-else>
					<view class="rightL">
						<view class="top">合计：<text class="pls"><text>¥</text>{{Number(totalPrice).toFixed(2)}}</text></view>
						<view class="">（不含运费和优惠券）</view>
					</view>
					<view class="rightR" @click="goPrice()">
						去结算（{{chioseGoodsNum}}）
					</view>
				</view>
			</view>
		</template>
		<view class="noDate"  v-else>
			<image src="https://willmid-img.oss-cn-shanghai.aliyuncs.com/2021/10/13/2x-18.png" mode=""></image>
			<view class="">暂无商品~</view>
			<view class="goShop" @click="goShop()">去购物</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				totalPrice:0,
				idDelete:false,
				chioseGoodsNum:0,
				isAllCheck:false,
				carList:[],
				list: [
					{
						id: 1,
						title: '长安回望绣成堆，山顶千门次第开，一骑红尘妃子笑，无人知是荔枝来',
						images: 'https://cdn.uviewui.com/uview/common/logo.png',
						show: false
					},
					{
						id: 2,
						title: '新丰绿树起黄埃，数骑渔阳探使回，霓裳一曲千峰上，舞破中原始下来',
						images: 'https://cdn.uviewui.com/uview/common/logo.png',
						show: false
					},
					{
						id: 3,
						title: '登临送目，正故国晚秋，天气初肃。千里澄江似练，翠峰如簇',
						images: 'https://cdn.uviewui.com/uview/common/logo.png',
						show: false,
					}
				],
				options: [
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				scrollTop: 0
			}
		},
		onPageScroll(e){
			this.scrollTop = e.scrollTop
		},
		async onLoad() {
			this.getCarList()
		},
		methods: {
			dataTime(num) {
				// 获取当前日期
				let currentDate = new Date();
				
				// 将日期加一天
				currentDate.setDate(currentDate.getDate() + num);
				
				// 获取年月日
				let year = currentDate.getFullYear();
				let month = String(currentDate.getMonth() + num).padStart(2, '0'); // 月份是从0开始的，所以加1
				let day = String(currentDate.getDate()).padStart(2, '0');
				
				// 格式化为 年-月-日
				let formattedDate = `${year}-${month}-${day}`;
				return formattedDate
			},
			// 去结算
			async goPrice(){
				let goosArr = []
				this.carList.forEach((ele)=>{
					if(ele.isCheck){
						goosArr.push({
							sku_id:ele.sku_id,
							number:ele.number
						})
					}
				})
				if(goosArr.length){
					// let sku = {
					// 	skus:JSON.stringify(goosArr)
					// }
					// let {code,data} = await this.$u.api.confirmOrder(sku);
					// if(code){
						this.$u.vuex('goodsInfo', "")
						this.$u.vuex("toStore","")
						this.$u.vuex("toStore_id","")
						this.$u.route('/pages/shop/shopOrder?is_cart=1&skus=' + JSON.stringify(goosArr));
					// }
				}else{
					this.utlis.Toast('请勾选要结算的商品')
				}
			},
			// 去购物
			goShop(){
				uni.switchTab({
					url:"index"
				})
			},
			// 全选
			allCheck(){
				let total = 0
				let num = 0
				if(this.isAllCheck){
					this.carList.forEach((ele)=>{
						ele.isCheck = false
					})
					this.chioseGoodsNum = 0
					this.totalPrice = 0
				}else{
					this.carList.forEach((ele)=>{
						console.log(555, ele)
						if (ele.sku.stock > 0) {
							ele.isCheck = true
							num++
							if(this.userInfo.vip_id >= 1){
								total = total + ele.sku.vip_price * ele.number
							}else{ 
								total = total + ele.sku.sale_price * ele.number
							}
						}
					})
					this.totalPrice = total
					this.chioseGoodsNum = num
				}
				this.isAllCheck = !this.isAllCheck
			},
			// 单选
			choice(item){
				item.isCheck = !item.isCheck
				this.count()
			},
			// 选择数量计算
			count(){
				let total = 0
				let arr = []
				this.carList.forEach((ele)=>{
					if(ele.isCheck){
						arr.push(ele)
						if(this.userInfo.vip_id >= 1){
							total = total + ele.sku.vip_price * ele.number
						}else{ 
							total = total + ele.sku.sale_price * ele.number
						}
					}
				})
				this.totalPrice = total
				this.chioseGoodsNum = arr.length
				if(arr.length == this.carList.length){
					this.isAllCheck = true
				}else{
					this.isAllCheck = false
				}
				this.$forceUpdate()
			},
			async reduce(ele){
				if(ele.number == 1){
					this.utlis.Toast('至少要购买一件')
				}else{
					ele.number--
					console.log(ele.number,"number--number--")
					let {data,code} = await this.$u.api.updateNumber({id:ele.id,number:ele.number});
					this.utlis.Toast('数量更新成功',"success")
					this.count()
				}
			},
			async plus(ele){
				if(ele.number >= ele.sku.stock){
					this.utlis.Toast('库存不足')
				}else{
					ele.number++
					console.log(ele.number,"number++number++")
					let {data,code} = await this.$u.api.updateNumber({id:ele.id,number:ele.number});
					this.utlis.Toast('数量更新成功',"success")
					this.count()
				}
			},
			// 获取购物车列表
			async getCarList(){
				let {data,code} = await this.$u.api.carLists();
				data.forEach((ele)=>{
					ele.show = false
					ele.isCheck = false
				})
				this.carList = data
				console.log(data,"data")
			},
			// 批量删除
			async batchDele(){
				let arr = []
				this.carList.forEach((ele)=>{
					if(ele.isCheck){
						arr.push(ele.id)
					}
				})
				let ids 
				if(arr.length){
					 ids = arr.join(",")
				}else{
					this.utlis.Toast('请选择要删除的商品')
					return
				}
				uni.showModal({
				    title: '提示',
				    content: '您确定要删除选中的商品？',
					confirmColor:'#007664',
				    success: async (res) => {
				        if (res.confirm) {
				            let {data,code} = await this.$u.api.delCars({id:ids});
				            if(code){
								await this.getCarList()
								await this.count()
								this.isAllCheck = false
				            	this.utlis.Toast('删除成功',"success")
				            }
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
			async deCar(index, index1) {
				uni.showModal({
				    title: '提示',
				    content: '您确定要删除此商品？',
					confirmColor:'#007664',
				    success: async (res) => {
				        if (res.confirm) {
				            let {data,code} = await this.$u.api.delCars({id:JSON.stringify(this.carList[index].id)});
				            if(code){
				            	this.carList.splice(index,1)
				            	this.utlis.Toast('删除成功',"success")
				            }
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
				
			},
			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(index) {
				// console.log(111111111)
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.carList[index].show = true;
				this.carList.map((val, idx) => {
					if(index != idx) this.carList[idx].show = false;
				})
			}
		}
	}
</script>

<style lang="scss" scoped >
.container{
	padding: 50rpx 30rpx;
	.noDate{
		position: absolute;
		top: 40%;
		left: 50%;
		transform: translate(-50%,-50%);
		color: #666666;
		font-size: 26rpx;
		text-align: center;
		image{
			width: 360rpx;
			height: 310rpx;
			margin-bottom: 78rpx;
		}
		.goShop{
			width: 236rpx;
			height: 70rpx;
			background: linear-gradient(140deg,#50DCC2 0%, #007664);
			border-radius: 48rpx;
			margin: 34rpx auto 0;
			color: #FFFFFF;
			font-size: 28rpx;
			line-height: 70rpx;
		}
	}
	.icon-a-xingzhuang1{
		color: #007664;
		font-size: 36rpx !important;
	}
	.icon-weixuanzhong{
		color: #979797;
		font-size: 36rpx !important;
	}
	.fixedBottom{
		position: fixed;
		width: 750rpx;
		bottom: 0;
		height: 207rpx;
		display: flex;
		justify-content: space-between;
		padding: 35rpx 32rpx 0 43rpx;
		box-sizing: border-box;
		left: 0;
		background: #ffffff;
		box-shadow: 0px 0px 13rpx 0px rgba(110,126,189,0.18); 
		.right{
			display: flex;
			justify-content: space-between;
			.rightL{
				color: #666666;
				font-size: 20rpx;
				margin-right: 22rpx;
				text-align: center;
				.top{
					color: #333333;
					font-size: 24rpx;
					.pls{
						color: #007664;
						font-size: 30rpx;
						text{
							font-size: 20rpx;
							margin-right: 5rpx;
						}
					}
					
				}
			}
			.rightR{
				width: 200rpx;
				height: 80rpx;
				background: linear-gradient(90deg, #50DCC2 0%, #007664 100%);
				border-radius: 53rpx;
				line-height: 80rpx;
				text-align: center;
				color: #FFFFFF;
				font-size: 28rpx;
			}
		}
		.left{
			color: #666666;
			font-size: 34rpx;
			height: 70rpx;
			line-height: 70rpx;
			.all{
				margin-left: 20rpx;
			}
		}
	}
	.shopCarWrap{
		padding-bottom: 260rpx;
		.list{
			// width: 680rpx;
			border-radius: 8rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			position: relative;
			>text{
				display: block;
			}
			.grayOut{
				opacity: 0.6;
				border-radius: 20rpx;
				height: 220rpx;
				padding: 20rpx 16rpx;
				overflow: hidden;
				position: absolute;
				top: 0;
				width: 100%;
				background: rgba(0,0,0,0.7) !important;
				font-size: 32rpx;
				color: white;
				text-align: center;
				line-height: 180rpx;
			}
			.right{
				width: 100%;
				background: #ffffff;
				border-radius: 20rpx;
				display: flex;
				margin-left: 19rpx;
				padding: 20rpx 16rpx;
				image{
					width: 176rpx;
					height: 176rpx;
					border-radius: 20rpx;
					flex: none;
					margin-right: 20rpx;
				}
				.bottom{
					display: flex;
					justify-content: space-between;
					align-items: center;
					.price{
						font-size: 30rpx;
						color: #007664;
						line-height: 42rpx;
						margin-right: 10rpx;
						text{
							font-size: 20rpx;
							margin-right: 5rpx;
						}
					}
				}
				.stock{
					color: #999999;
					font-size: 22rpx;
					// margin-bottom: 8rpx;
					margin-left: -50rpx;
				}
				.shopInfo{
					// padding: 29rpx 29rpx 29rpx 0;
					width: 390rpx;
					// border: 1rpx solid green;
					.shopName{
						font-size: 26rpx;
						color: #071529;
						line-height: 37rpx;
						margin-bottom: 5rpx;
						font-weight: bold;
					}
					.number{
						display: flex;
						align-items: center;
						// border: 1rpx solid red;
						.reduce{
							width: 30rpx;
							height: 30rpx;
							text-align: center;
							line-height: 30rpx;
							background-color: #ededed;
							color: #b9b9b9;
						}
						.num{
							color: #333333;
							font-size: 28rpx;
							margin: 0rpx  18rpx 0 19rpx;
						}
						.plus{
							width: 30rpx;
							height: 30rpx;
							line-height: 30rpx;
							text-align: center;
							line-height: 30rpx;
							background: #007664;
							color: #FFFFFF;
						}
					}
					.skrWrap{
						display: flex;
						align-items: center;
						margin-bottom: 10rpx;
						.skr{
							// width: 360rpx;
							font-size: 22rpx;
							color: #999999;
							padding:7rpx 16rpx ;
							line-height: 33rpx;
							background: rgba(194,194,194,.1);
							border-radius: 8rpx;
							overflow: hidden; 
							text-overflow:ellipsis;    
							white-space: nowrap;
						}
						.time{
							color: #E5C372;
							font-size: 20rpx;
							image{
								width: 23rpx;
								height: 23rpx;
								position: relative;
								top: 3rpx;
								margin-right: 5rpx;
							}
						}
					}
				}
			}
		}
	}
	.title{
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-left: 10rpx;
		margin-bottom: 34rpx;
		.checkNum{
			color: #666666;
			font-size: 26rpx;
			margin-top: 10rpx;
			font-weight: bold;
			text{
				color: #007664;
				margin: 0 8rpx;
			}
		}
		.edit{
			color: #007664;
			font-weight: bold;
		}
	}
}
</style>
<style >
page{
	background-color: #F6F7FA;
}
</style>
